package com.bruce.apkinstaller.install;

import android.content.pm.IPackageInstallObserver;
import android.os.RemoteException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/1/11.
 */

public class ProductPmInstallImpl extends APminstallbaseImpl implements InPmInstallImpl {
    private static final String TAG = ProductPmInstallImpl.class.getSimpleName();
    private PmPakcageInstallObserver mPakcageInstallObserver;

    @Override
    public void setInstallCallback(ArrayList<String> apklist, InstallStatusCallback installCallback) {
        mInstallCallback = installCallback;
        mApklist = apklist;
        mPakcageInstallObserver = new PmPakcageInstallObserver();
    }

    @Override
    public void start() {
        start(mApklist.get(0));
    }

    @Override
    public void start(String apkfile) {
        install(apkfile, mPakcageInstallObserver);
    }

    @Override
    public void setInstallCallback(InstallStatusCallback installCallback) {
        mPakcageInstallObserver = new PmPakcageInstallObserver();
        mInstallCallback = installCallback;
    }

    @Override
    public void install(String apkAbsolutePath, PmPakcageInstallObserver observer) {
        PmInstallerModel.pmInstall(apkAbsolutePath, observer);
    }

    public class PmPakcageInstallObserver extends IPackageInstallObserver.Stub {
        @Override
        public void packageInstalled(String s, int i) throws RemoteException {
            if (i == 1) {
                mInstallCallback.success(s);
                if (mApklist.size() > 1) {
                    mInstallCallback.progress(s, (int) (((double) finishedCount / (mApklist.size() - 1)) * 100));
                } else {
                    mInstallCallback.progress(s, 100);
                }
                installNext();
            } else {
                mInstallCallback.failure(s, i);
                installNext();
            }
        }
    }
}
